package cn.itcast.bos.service.transit.impl;

import org.springframework.transaction.annotation.Transactional;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import cn.itcast.bos.dao.take_delivery.WayBillRepository;
import cn.itcast.bos.dao.transit.TransitInfoRepository;
import cn.itcast.bos.domain.take_delivery.WayBill;
import cn.itcast.bos.domain.transit.TransitInfo;
import cn.itcast.bos.index.WayBillIndexRepository;
import cn.itcast.bos.service.transit.TransitInfoService;

@Service
@Transactional
public class TransitInfoServiceImpl implements TransitInfoService {

	@Autowired
	private TransitInfoRepository transitInfoRepository;

	@Autowired
	private WayBillRepository wayBillRepository;
	
	@Autowired
	private WayBillIndexRepository wayBillIndexRepository;

	@Override
	public void createTransits(String waybillIds) {
		if (StringUtils.isNotBlank(waybillIds)) {
			String[] wayBillArrayIds = waybillIds.split(",");
			for (String waybillId : wayBillArrayIds) {
				System.out.println(waybillId+"................");
				WayBill oneWayBill = wayBillRepository.findOne(Integer.parseInt(waybillId));
				System.out.println(oneWayBill);
				// 判断运单是否是待发货
				if (oneWayBill.getSignStatus() == 1) {
					// 待发货
					// 生成TransitInfo信息
					TransitInfo transitInfo = new TransitInfo();
					transitInfo.setWayBill(oneWayBill);
					transitInfo.setStatus("出入库中转");
					transitInfoRepository.save(transitInfo);

					// 更改运单状态为派送中
					oneWayBill.setSignStatus(2);
					
					//更新索引库
					wayBillIndexRepository.save(oneWayBill);
				}else{
					//已经发货
					throw new RuntimeException("运单已经发货,不能在修改了");
				}
			}
		}
	}

	@Override
	public Page<TransitInfo> findpageData(Pageable pageable) {
		return transitInfoRepository.findAll(pageable);
	}

}
